<template>
  <view class="pageBg pdb120 box-b">
    <view class="pd262830 box-b">
      <!--  解析地址    -->
      <view class="bgff radius12 pd034 box-b">
        <view class="h243 box-b flex1">
          <c-textarea
            v-model="copyContent"
            class="h243 pd3200 bdbd9 box-b color1a w100 lh30 fs24 disb"
            placeholder-class="fs24 colorcc"
            :max="500"
            placeholder="请在此处粘贴"
          ></c-textarea>
        </view>
        <view class="flex jsend pd2400 box-b">
          <c-botton
            name="识别"
            :className="['btn-close radius23 pd034 flex-box fs24 minh46 lh26 tac ffmi mgl16 background-sub white ',
              btnDisabledAnalysis ? 'bgd2' : '']"
            @click="!btnDisabledAnalysis && analysis()">
          </c-botton>
        </view>
<!--        <view class="flex jsend pd2400 box-b">-->
<!--          <c-botton-->
<!--            name="粘贴并识别"-->
<!--            :className="['btn-close radius23 pd034 flex-box fs24 minh46 lh26 tac ffmi mgl16 background-sub white ',-->
<!--              btnDisabledAnalysis ? 'bgd2' : '']"-->
<!--            @click="!btnDisabledAnalysis && analysisPaste()">-->
<!--          </c-botton>-->
<!--        </view>-->
      </view>

      <view class="bgff radius12 pd483452 box-b mgt22">
        <view class="betweenBox">
          <view class="flex-align flex1">
            <cInput
              v-model="recvname"
              :requireRed="true"
              :showClear="false"
              :textNameShow="true"
              textName="姓名"
              textClass="fs24 lh24 mgb16 flex-align color26"
              placeholder="请输入真实姓名"
              class="w100"
              bgDefultColor="bdbd9"
              pdClass=""
              inputHeight="h46"
            ></cInput>
          </view>
          <view class="flex-align flex18 mgl66">
            <cInput
              v-model="mob"
              :requireRed="true"
              :showClear="false"
              :textNameShow="true"
              textName="手机号码"
              textClass="fs24 lh24 mgb16 flex-align color26"
              placeholder="请输入手机号码"
              class="w100"
              bgDefultColor="bdbd9"
              pdClass=""
              inputHeight="h46"
            ></cInput>
          </view>
        </view>
        <view class="box-b flex1 mgt68" @click="showSheetView = true">
          <text-item className="fs24 color26 mgb16" title="省市区"></text-item>
          <view class="flex-align flex1">
            <view class="betweenBox bdbe7 flex1 h46">
              <view class="flex1  fs24">
                <view v-if="zone" class="fs24 color26">
                  {{ zone }}
                </view>
                <view v-else class="fs24">选择省市区</view>
              </view>
              <view>
                <server-image
                  class="img1018 disb"
                  name="repair/20241028004.png"
                  mode="aspectFill"
                ></server-image>
              </view>
            </view>
            <view
              v-if="false"
              class="flex jsend bdlcc pdl23 mgl23">
              <view>
                <server-image
                  class="img2734 disb"
                  name="repair/20241028013.png"
                  mode="aspectFill"
                ></server-image>
              </view>
            </view>
          </view>
        </view>
        <!--      <view class="box-b flex-align flex1 h100l mgt40">-->
        <!--        <view class="betweenBox flex1">-->
        <!--          <view-->
        <!--            class="flex1 bdbe7">-->
        <!--            <uni-data-picker-->
        <!--              placeholder="选择省市区"-->
        <!--              popup-title="请选择城市"-->
        <!--              collection="opendb-city-china"-->
        <!--              field="code as value, name as text"-->
        <!--              orderby="value asc"-->
        <!--              :step-searh="true"-->
        <!--              self-field="code"-->
        <!--              parent-field="parent_code"-->
        <!--              @change="onchange"-->
        <!--              @nodeclick="onnodeclick">-->
        <!--            </uni-data-picker>-->
        <!--          </view>-->
        <!--          <view>-->
        <!--            <server-image class="img40 disb" name="20230824002.png" mode="aspectFill"></server-image>-->
        <!--          </view>-->
        <!--        </view>-->
        <!--        <view class="flex jsend mgl20">-->
        <!--          <view>-->
        <!--            <server-image class="img40 disb" name="20230824002.png" mode="aspectFill"></server-image>-->
        <!--          </view>-->
        <!--        </view>-->
        <!--      </view>-->
        <view class="flex-align flex1">
          <cInput
            v-model="address"
            :requireRed="true"
            :showClear="false"
            placeholder="输入详细地址"
            class="w100 mgt30"
            bgDefultColor="bdbd9"
            pdClass=""
            inputHeight="h46"
          ></cInput>
        </view>

      </view>

<!--      <view v-if="!mustDefault" class="betweenBox mgt20 bgff radius12 minh102 pd034 box-b">-->
<!--        <view class="label fs28 color1a">设为默认地址</view>-->
<!--        <switch color="#0095FF" style="transform: scale(0.6)" checked @change="switchChange" />-->
<!--      </view>-->

    </view>

    <!--          <my-city-picker-->
    <!--            ref="mpvueCityPicker"-->
    <!--            :picker-value-default="pickerValueDefault"-->
    <!--            @onConfirm="onConfirm"-->
    <!--          />-->

<!--    <view class="w690 mga flex-box">-->
<!--      <view-->
<!--        class="w570 h90 flex-box background-sub white radius45 fw400 fs34 ffmi ltsp8 mg55a20"-->
<!--        :class="{ 'bgd2': btnDisabled }"-->
<!--        @click="!btnDisabled && editAddress()"-->
<!--      >-->
<!--        添加地址-->
<!--      </view>-->
<!--    </view>-->

    <repair-status
      btnName="添加地址"
      :btnDisabled="btnDisabled"
      @toOrder="!btnDisabled && editAddress()">
    </repair-status>

    <!-- 省市区  -->
    <uni-region-sheet
      ref="zxpUniRegionSheet"
      :class="['flex1 bdbe7', showSheetView ? 'visi' : 'vish']"
      :showSheetView="showSheetView"
      :defaultIndexs="defaultIndexs"
      @onSelected="onSelected"
      @onSelectedError="onSelectedError"
    ></uni-region-sheet>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import cInput from '@/components/c-input';
import cTextarea from '@/components/c-textarea';
import uniRegionSheet from '@/components/zxp-uniRegionSheet.vue';
// import myCityPicker from '@/components/myCityPicker.vue';
import repairStatus from '@/pages/member/components/repair-status';

// 解析地址
import AddressParse from 'address-parse';
import { uniGetClipboardData } from '@/common/utils';

export default {
  components: {
    cInput,
    cTextarea,
    uniRegionSheet,
    repairStatus,
    // myCityPicker,
  },
  data() {
    return {
      pickerValueDefault: [0, 0, 0],
      zone: '',
      setAsDefault: true,
      newAddress: true,
      recvname: '',
      mob: '',
      isDefault: '',
      address: '',
      province: '',
      city: '',
      district: '',
      cityIds: [],
      id: null,
      countryCodeIndex: 0,
      allowRequest: true,
      mustDefault: false,
      // region: [],
      showSheetView: false,
      defaultIndexs: [0, 0, 0],
      // 解析地址
      copyContent: '',
      againClick: true, //禁止数据频繁切换
    };
  },
  computed: {
    ...mapState({
      memberInfo: (state) => state.memberInfo || {},
      // countryCodeList: (state) => state.countryCode || [],
      // countryCodeTxtAndCodeList() {
      //   return this.countryCodeList.map((v) => `${v.countryName} ${v.countryCode}`);
      // },
      // countryCodeTxtList() {
      //   return this.countryCodeList.map((v) => v.countryCode);
      // },
      // countryCode() {
      //   return this.countryCodeTxtList[this.countryCodeIndex];
      // },
    }),
    btnDisabled: function () {
      let vm = this;
      return !vm.recvname || !vm.mob || !vm.zone || !vm.address;
    },
    btnDisabledAnalysis: function () {
      let vm = this;
      return !vm.copyContent || !vm.againClick;
    },
  },
  onLoad(e) {
    if (e.id) {
      this.id = e.id;
      this.getAddress();
    }
    if (e.mustDefault == 1) {
      this.mustDefault = true;
      this.setAsDefault = true;
    }
    if(e&&e.addressObj){
      const vm = this
      let addressObj = JSON.parse(e.addressObj);
      vm.recvname = addressObj.recvname;
      vm.mob = addressObj.mob;
      vm.zone = addressObj.province+addressObj.city+addressObj.district;
      vm.address = addressObj.address;
      vm.city = addressObj.city;
      vm.district = addressObj.district;
      vm.province = addressObj.province;
      vm.defaultIndexs = addressObj.defaultIndexs;
      // 默认选中地址
      if (this.$refs && this.$refs.zxpUniRegionSheet) {
        let result = {
          province: addressObj.province,
          city: addressObj.city,
          area: addressObj.district,
        }
        this.$refs.zxpUniRegionSheet.searchName(result);
      }
    }
    // this.getCountryList();
  },
  methods: {
    ...mapActions(['getCountryList']),
    // 识别解析地址
    analysis: function () {
      const vm = this;
      if(!vm.copyContent){
        return uni.showToast({
          title: '请粘贴您需要识别的地址',
          icon: 'none'
        })
      }
      vm.againClick = false
      const resultAddress = AddressParse.parse(vm.copyContent)
      let result = ''
      if(resultAddress && resultAddress.length){
        let html = ''
        for(let key in resultAddress[0]){
          if(resultAddress[0][key]){
            html+=key+`:`+resultAddress[0][key]+`<br/>`
          }
        }
        // result = JSON.stringify(resultAddress[0])
        result = resultAddress[0]
      }
      console.log('result', result);
      if(result){
        // 省市区自动选中对应名称
        if (this.$refs && this.$refs.zxpUniRegionSheet
          && result.province && result.city && result.area) {
          vm.province = result.province;
          vm.city = result.city;
          vm.district = result.area;
          // vm.region = [result.province, result.city, result.area];
          vm.zone = vm.province+vm.city+vm.district
          this.$refs.zxpUniRegionSheet.searchName(result,true);
        }
        if (/\s/g.test(result.name)) {
          vm.recvname = vm.getStringBeforeSpace(result.name);
        } else {
          vm.recvname = result.name;
        }
        vm.mob = result.mobile || result.phone;
        if(result.details && result.province && result.city && result.area){
          vm.address = result.details;
        }
      }
      vm.sleep(1500).then(() => {
        vm.againClick = true;
      });
    },
    // 剪切板解析
    // analysisPaste: function () {
    //   const vm = this;
    //   vm.againClick = false
    //   // 获取剪贴板的内容
    //   uniGetClipboardData({
    //     success: (res) => {
    //       // vm.copyContent = res.data;
    //       if (!res.data){
    //         uni.hideToast();
    //         return;
    //       }
    //       const result = AddressParse.parse(res.data)[0];
    //       console.log('result', result);
    //       vm.province = result.province;
    //       vm.city = result.city;
    //       vm.district = result.area;
    //       // vm.region = [result.province, result.city, result.area];
    //       vm.zone = vm.province+vm.city+vm.district
    //       if (this.$refs && this.$refs.zxpUniRegionSheet
    //         && vm.province && vm.city && vm.district) {
    //         this.$refs.zxpUniRegionSheet.searchName(result,true);
    //       }
    //       if (/\s/g.test(result.name)) {
    //         vm.recvname = vm.getStringBeforeSpace(result.name);
    //       } else {
    //         vm.recvname = result.name;
    //       }
    //       vm.mob = result.mobile || result.phone;
    //       if(result.details && vm.province && vm.city && vm.district){
    //         vm.address = result.details;
    //       }
    //       if(res.data && vm.province && vm.city && vm.district){
    //         vm.copyContent = res.data;
    //       }
    //       // 因为微信小程序会自带一个弹窗,所以可以选择覆盖或者是隐藏
    //       uni.hideToast();
    //       // 覆盖
    //       // uni.showToast({
    //       // 	title:"复制成功"
    //       // })
    //     },
    //     fail: function (err) {
    //       console.log(err);
    //       const { errMsg } = err;
    //       if(errMsg) {
    //         vm.showMessage({
    //           title: errMsg || 'getClipboardData API 失效',
    //           icon: 'error',
    //           duration: 1500,
    //         });
    //       }
    //     },
    //   });
    //
    //   vm.sleep(1500).then(() => {
    //     vm.againClick = true;
    //   });
    // },
    countryCodeChange(e) {
      this.countryCodeIndex = e.detail.value;
    },
    showCityPicker() {
      this.$refs.mpvueCityPicker.show();
    },
    switchChange(e) {
      this.setAsDefault = e.detail.value;
    },
    onConfirm(e) {
      // console.log(e);
      this.zone = e.label;
      this.cityIds = e.cityCode;
    },
    getAddress() {
      uni.showLoading({
        title: '加载中...',
      });
      this.apiUrl
        .getAddressById({
          data: {
            id: this.id,
          },
        })
        .then((res) => {
          uni.hideLoading()
          // console.log(res);
          const { code, data } = res.data;
          if(code == 0 && data){
            this.zone = data.position || (data.province+data.city+data.district);
            this.recvname = data.recvname;
            this.mob = data.mob;
            this.address = data.address;
            this.cityIds = [data.province, data.city, data.district];
            this.countryCode = data.countryCode;
          }
        });
    },
    editAddress() {
      let vm = this;
      const data = {
        memberId: vm.memberInfo.id,
        recvname: vm.recvname,
        address: vm.address,
        mob: vm.mob,
        position: vm.zone,
        // isDefault: vm.setAsDefault ? 1 : 0,
        // city: vm.cityIds[1],
        // district: vm.cityIds[2],
        // province: vm.cityIds[0],
      };
      if (!data.recvname || !data.mob || !data.position || !data.address) {
        let showdata = '';
        if (!data.address) showdata = '详细地址';
        if (!data.position) showdata = '省市区';
        if (!data.mob) showdata = '手机号';
        if (!data.recvname) showdata = '姓名';
        uni.showToast({
          title: `${showdata}不能为空`,
          duration: 2000,
          icon: 'none',
        });
        return;
      }
      if (!vm.isValidPhoneNumber(data.mob)) {
          uni.showToast({
            title: `请输入正确手机号`,
            duration: 2000,
            icon: 'none',
          });
          return;
      }

      if (vm.id) {
        data.id = vm.id;
      }
      let returnAddress = [vm.recvname, vm.mob, vm.zone + vm.address].join(',');
      let addressObj = {
        returnAddress: returnAddress,
        recvname: vm.recvname,
        mob: vm.mob,
        zone: vm.zone,
        address: vm.address,
        city: vm.city,
        district: vm.district,
        province: vm.province,
        defaultIndexs: vm.defaultIndexs,
      }

      // 暂时不请求接口 start
      if (!this.allowRequest) return;
      this.allowRequest = false;
      uni.showLoading({
        title: '加载中...',
      });
      vm.showMessage({ title: '提交地址成功', icon: 'success' }).then(() => {
        uni.hideLoading();
        uni.setStorageSync('repairReportAddress', JSON.stringify(addressObj));
        // 缓存用户地址
        uni.setStorageSync('memberAddress', JSON.stringify(addressObj));
        vm.goBack();
      });
      vm.sleep(1500).then(() => {
        vm.allowRequest = true;
      });
      return;
      // 暂时不请求接口 end


      if (!this.allowRequest) return;
      this.allowRequest = false;
      uni.showLoading({
        title: '加载中...',
      });
      this.apiUrl
        .submitAddress({
          data: {
            ...data,
            // countryCode: vm.countryCode,
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code, msg: message = '' } = res.data;
          if (code == 0) {
            // vm.$store.dispatch('getAddressInfo');
            let returnAddress = [vm.recvname, vm.mob, vm.zone + vm.address].join(',');
            let addressObj = {
              returnAddress: returnAddress,
              recvname: vm.recvname,
              mob: vm.mob,
              zone: vm.zone,
              address: vm.address,
              city: vm.city,
              district: vm.district,
              province: vm.province,
              defaultIndexs: vm.defaultIndexs,
            }
            vm.showMessage({ title: '提交地址成功', icon: 'success' }).then(() => {
              uni.setStorageSync('repairReportAddress', JSON.stringify(addressObj));
              // 缓存用户地址
              uni.setStorageSync('memberAddress', JSON.stringify(addressObj));
              vm.goBack();
            });
          } else {
            vm.showMessage({
              title: message,
              // icon: 'error',
              duration: 1500,
            });
          }
        })
        .finally(() => {
          vm.sleep(1500).then(() => {
            vm.allowRequest = true;
          });
        });
    },
    onchange(e) {
      const value = e.detail.value;
      console.log('value', value);
    },
    onnodeclick(node) {},
    onSelected(row) {
      /*这里必须将值置为false，否则无法唤起下一次的弹框显示*/
      const vm = this
      console.log('row', row);
      const { data } = row
      if (row && row.confirm && data) {
        vm.zone = data.text;
        vm.city = data.city;
        vm.district = data.area;
        vm.province = data.province;
        vm.defaultIndexs = data.defaultIndexs;
      }
      this.showSheetView = false;
    },
    onSelectedError(row) {
      /*这里必须将值置为false，否则无法唤起下一次的弹框显示*/
      const vm = this
      console.log('row', row);
      if (row && row.confirm) {
        vm.zone = '';
        vm.city = '';
        vm.district = '';
        vm.province = '';
        vm.defaultIndexs = [0,0,0];
        vm.showMessage({
          title: '识别省市区格式错误：请手动选择',
          duration: 1500,
        });
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
